package com.itheima.app.controller;

import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    UserManager userManager;

    @PostMapping("user/save")
    public Long save(@RequestBody User user){
        return userManager.save(user);
    }

    @GetMapping("user/findByPhone")
    public User findByPhone(String phone){
        if (phone.equals("0")) {
            int i=1/0;
        }
        return userManager.findByPhone(phone);
    }

    @PostMapping("/user/login")
    //发送手机验证码
    public ResponseEntity sendCode(@RequestBody Map<String,String> map){
        String phone = map.get("phone");
        return userManager.sendCode(phone);
    }

    @PostMapping("/user/loginVerification")
    //注册登陆
    public ResponseEntity regAndLogin(@RequestBody Map<String,String> map){
        return userManager.regAndLogin(map);
    }


    @PostMapping("/user/loginReginfo")
    //保存用户基本信息
    public ResponseEntity saveUserInfo(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token){
        return  userManager.saveUserInfo(userInfo,token);
    }

    @PostMapping({"/user/loginReginfo/head","/users/header"})
    //更新用户头像
    public ResponseEntity saveOrUpdatePhoto(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
        return userManager.saveOrUpdatePhoto(headPhoto,token);
    }

    @GetMapping("/users")
    //获取用户信息
    public ResponseEntity findUserInfoById(@RequestParam(required = false) Long userID,@RequestHeader("Authorization")String token){
        if (null != userID) {
            return userManager.findUserInfoById(userID);
        }else {
            User user = userManager.findUserFormToken(token);
            if (user == null) {
                return ResponseEntity.status(401).body(null);
            }

            return userManager.findUserInfoById(user.getId());
        }
    }

    @PutMapping("/users")
    //更新用户信息
    public ResponseEntity updateUserInfo(@RequestBody UserInfo userInfo,@RequestHeader("Authorization")String token){
        return userManager.updateUserInfo(userInfo,token);
    }
}
